<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit" :showHistoryBtn="true">
		<om-autoform ref="autoform" :checkedit="checkedit" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
		<om-white-space bgColor="#eee"></om-white-space>
	</om-addpage>
</template>

<script>
import { getUrl,confirmModal, ptFloat, minusF ,dealBigMoney,errorModal} from '@/static/js/common.js';
import { buildFormData, formValidation, tranferToEditors, changeEditor,setSubmitSubValue, configSelectData, hasValue,formShowLoading ,getFormFields,formModelLoad,getWorkCacheKey, getEditor, getEditorTitle} from '@/static/js/formUtil.js';
import urlUtil from '@/static/js/urlUtil.js';
import { mapState } from 'pinia';
import {useLoginUserStore} from '@/stores/login-user.js';
import moment from '@/static/js/moment.js'
export default {
	provide() {
		return {
			formPage: this
		};
	},
	data() {
		return buildFormData({
			initValue: {
				paySum:"",
				dataStr:""
			},
			formdata: {
				paySum:""
			},
			userCacheKey:"fin-bx-travels-user-cache",
			currencyCache:'fin-bx-travels-currency-cache',
			bankUserCacheKey:'fin-bx-travels-bankUser-cache',
			
		})
	},
	computed: {
		...mapState(useLoginUserStore, ['userName', 'userId'])
	},
	methods: {
		watchInput1(val){
			let _that = this
			let formdata = _that.$refs.autoform.formdata
			if(formdata.returnNum){
				_that.$refs.autoform.clear("title1","returnNum")
			}
			let title1 = _that.$refs.autoform.getEditorTitle("title1","payNum")
			let title2 = _that.$refs.autoform.getEditorTitle("title1","paySum")
			if(Number(val) > Number(formdata.paySum)){
				errorModal(_that,'提示信息',title1+'不能大于'+ title2,()=>{
					_that.$refs.autoform.clear("title1","payNum")
					_that.$refs.autoform.clear("title1","capitalPaySum")
				})
			}
			_that.$refs.autoform.formdata.capitalPaySum = dealBigMoney(val)
		},
		watchInput(val){
			let _that = this
			let formdata = _that.$refs.autoform.formdata
			if(formdata.payNum){
				_that.$refs.autoform.clear("title1","payNum")
			}
			if(Number(val)>(Number(formdata.planPaySum) - Number(formdata.paySum))){
				let title1 = _that.$refs.autoform.getEditorTitle("title1","returnNum")
				let title2 = _that.$refs.autoform.getEditorTitle("title1","planPaySum")
				let title3 = _that.$refs.autoform.getEditorTitle("title1","paySum")
				errorModal(_that,'提示信息',title1+'不能大于'+'('+ title2 +'-'+title3+')',()=>{
					_that.$refs.autoform.clear("title1","returnNum")
				})
			}
		},
		getDays(list){
			let _that = this
			_that.om.request(
				'travelExpensesForm/getDays',
				{
					dataStr:list
				},
				'POST'
			).then(res=>{
				if(res.value){
					_that.$refs.autoform.formdata.days = res.value
				}
			})
		},
		getTime(editor){
			let _that = this
			let dateTimes = []
			let st = ''
			let et = ''
			let list = editor.workList
			for(let item of list){
				if(item.fileList && item.fileList.length<1){
					delete item.fileList
				}
				if(item.startTime){
					item.startTime+= ':00'
					dateTimes.push(item.startTime )
				}
				if(item.endTime){
					item.endTime+= ':00'
					dateTimes.push(item.endTime )
				}
				if(item.planStartTime){
					item.planStartTime+= ':00'
				}
				if(item.planEndTime){
					item.planEndTime+= ':00'
				}
			}
			st = dateTimes[0]
			et = dateTimes[0]
			for(let index in dateTimes){
				if(dateTimes[Number(index) + 1] && moment(dateTimes[Number(index) + 1]).isSameOrBefore(dateTimes[index])){
					st = dateTimes[Number(index) + 1]
				}
				if(dateTimes[Number(index) + 1] && moment(dateTimes[Number(index) + 1]).isSameOrAfter(dateTimes[index])){
					et = dateTimes[Number(index) + 1]
				}
			}
			_that.$refs.autoform.formdata.endDate = et
			_that.$refs.autoform.formdata.startDate = st
			_that.getDays(JSON.stringify(editor.workList))
		},
		onSelectKeyPost(d){
			let _that = this
			_that.$refs.autoform.formdata.keyInstId = d.instId
			_that.$refs.autoform.formdata.keyInstName = d.instName
		},
		onSubChange(editor){
			let _that = this.$refs.autoform
			if(editor.workList.length) {
				_that.formdata.paySum = this._.sum(editor.workList.map(e=>ptFloat(e.sumCosts)))
			} else {
				_that.formdata.paySum = 0
			}
			this.getCapitalPaySum()
		},
		getCapitalPaySum(){
			this.verifyBackSum()
			this.calcPaySum()
			let _that = this.$refs.autoform
			var payNum = _that.formdata.payNum
			if(payNum){
				_that.om.request("common/getCapitalNum", {
					moneyNum: payNum
				}).then(res=>{
					if (res.succeed) {
						_that.formdata.capitalPaySum = res.value
					}
				})
			}else{
				_that.formdata.capitalPaySum = ""
			}
		},
		//计算退还金额
		verifyBackSum(item) {
			if(item){
				if(minusF(ptFloat(_that.formdata.loanSum),ptFloat(_that.formdata.selfPaySum)) < ptFloat(diff)){
					this.$refs.autoform.formdata.backSum = 0
				}
			}
		},
		//计算实付金额
		calcPaySum(){
			let _that = this.$refs.autoform
			let diff = minusF(ptFloat(_that.formdata.planPaySum),ptFloat(_that.formdata.paySum))
			_that.formdata.payNum = diff<0?Math.abs(diff):''
		},
		formSubmit() {
			let _that = this;
			_that.om.request("travelExpensesForm/verifyLoanMoney",_that.formdata,"post").then(res=>{
				if(res.succeed) {
					var obj = res.value;
					if(obj.msg){
						confirmModal(_that, '提示信息', obj.msg, _that.save);
					}else if(obj.flag){
						_that.save()
					}
				}else{
					_that.om.toast(res.msg)
				}
			})
		},
		save(){
			let _that = this;
			var arr = _that._.cloneDeep(_that.subEditorObj['title2'].workList)
			 for(var i=0;i<arr.length;i++){
				 var a = arr[i]
				 if(a.planStartTime){
					 a.planStartTime += ":00"
				 }
				 if(a.planEndTime){
					a.planEndTime += ":00"
				 }
				 if(a.startTime){
					 a.startTime += ":00"
				 }
				 if(a.endTime){
					a.endTime += ":00"
				 }
				 if(a.fileList && a.fileList.length<1){
					 delete a.fileList
				 }
				 if(!a.fileList){
					  delete a.fileList
				 }
			 }
			 //子表提交数据赋值
			 _that.formdata.dataStr = JSON.stringify(arr)
			if(this.checkedit) {
				_that.om.formSave('travelExpensesForm/doReviewUpdate', _that.formdata, _that)
			} else if(this.edit){
				_that.om.formSave('travelExpensesForm/doUpdate', _that.formdata, _that)
			} else {
				_that.om.formSave('travelExpensesForm/doAdd', _that.formdata, _that)
			}
		},
		getWorkParam() {
			return {
				checkedit:this.checkedit,
				bxUserId:this.formdata.keyUserId,
				instId:this.formdata.keyInstId,
				instName:this.formdata.keyInstName
			};
		},
		onSelectUser(item){
			let _that = this;
			//加载借款金额
			_that.om.request("loanList/getLoanSumByUserId", {
				userId: item.userId
			}).then(res => {
				if (res.succeed) {
					var value = res.value;
					_that.$refs.autoform.formdata.planPaySum = value
				} else {
					_that.$refs.autoform.formdata.planPaySum = ""
				}
			})
		},
		clearKeyUser(){
			var formdata  = this.$refs.autoform.formdata
			formdata.keyUserId = ""
			formdata.keyUserName = ""
			formdata.keyPostId = ""
			formdata.keyPostName = ""
			formdata.keyInstId = ""
			formdata.keyInstName = ""
		},
		onSelectPayType(item) {
			let _that = this;
			if(item.code == "37848"){
				_that.$refs.autoform.changeEditor("title1","payeeBankName","required",true)
				_that.$refs.autoform.changeEditor("title1","payeeBankNum","required",true)
			}else{
				_that.$refs.autoform.changeEditor("title1","payeeBankName","required",false)
				_that.$refs.autoform.changeEditor("title1","payeeBankNum","required",false)
			}
		},
		clearPayType(){
			let _that = this;
			_that.$refs.autoform.clear("title1","payTypeId")
			_that.$refs.autoform.changeEditor("title1","payeeBankName","required",false)
			_that.$refs.autoform.changeEditor("title1","payeeBankNum","required",false)
		},
		initLoad(options) {
			let _that = this;
			var ajaxArr = [
				urlUtil.zposUrl(options.code), 
				urlUtil.dictZeroComboboxUrl('37846'),
				{
					url:'currencyDict/getLocalCurrency',
				},
				{
					url:'loanList/getLoanSumByUserId',
					param:{
						userId: _that.userId
					}
				}
			];
			var fileId = options.fileId
			if(fileId){
				ajaxArr.push({
					url:"travelExpensesForm/getValue",
					param:{fileId:fileId}
				})
			}
			formModelLoad(ajaxArr, function(res, mainData) {
				changeEditor('topinfo', 'zposId', 'data', configSelectData(res[0], 'id', 'posName'), mainData);
				changeEditor('title1', 'keyPostId', 'data', configSelectData(res[0], 'id', 'posName'), mainData);
				changeEditor('topinfo', 'zuserId', 'defaultValue', _that.userId, mainData);
				changeEditor('topinfo', 'zuserId', 'defaultName', _that.userName, mainData);
				changeEditor('title1', 'keyUserId', 'defaultValue', _that.userId, mainData);
				changeEditor('title1', 'keyUserId', 'defaultName', _that.userName, mainData);
				changeEditor('title1', 'currencyId', 'defaultValue', res[2].value.id, mainData);
				changeEditor('title1', 'currencyId', 'defaultName',  res[2].value.codeNameUnit, mainData);
				changeEditor('title1', 'bankUserId', 'defaultValue', _that.userId, mainData);
				changeEditor('title1', 'bankUserId', 'defaultName', _that.userName, mainData);
				changeEditor('title1', 'payTypeId', 'data', configSelectData(res[1], 'id', 'dicname'), mainData);
				if(res[3].value > 0){
					changeEditor("title1","payNum","type","numberbox",mainData)
					changeEditor("title1","payNum","prompt","请输入",mainData)
					changeEditor("title1","returnNum","type","numberbox",mainData)
					changeEditor("title1","returnNum","prompt","请输入",mainData)
					changeEditor("title1","returnNum","watchInput","watchInput",mainData)
					changeEditor("title1","payNum","watchInput","watchInput1",mainData)
					changeEditor("title1",'planPaySum',{
						defaultName:res[3].value,
						defaultValue:res[3].value
					},null,mainData)
				}
				changeEditor('title1', "keyUserId","link","../../public/pageSearch/pageSearch", mainData)
				changeEditor('title1', "keyUserId", "linkParam", {
					other: JSON.stringify({
						firstUserId: _that.userId
					}),
					namefield:"userPosInstName",
					notefield:"userno",
					searchfield:"q",
					initload:true,
					url:"temployee/getStaffCombogrid",
					cachename:_that.userCacheKey,
					placeholder:"请输入姓名或岗位"
				}, mainData)
				changeEditor('title1', "bankUserId","link","../../public/pageSearch/pageSearch", mainData)
				changeEditor('title1', "bankUserId", "linkParam", {
					other: JSON.stringify({
						firstUserId: _that.userId
					}),
					namefield:"username",
					notefield:"userno",
					extrafield:"posInstName",
					searchfield:"q",
					initload:true,
					url:"temployee/getStaffCombogrid",
					cachename:_that.bankUserCacheKey,
					placeholder:"请输入姓名或岗位"
				}, mainData)
				
				changeEditor("title1","currencyId",{
					'link':'../../public/pageSearch/pageSearch',
					'linkParam':{
						other:JSON.stringify({
							
						}),
						url:'currencyDict/getCurrency',
						namefield:'currencyName',
						extrafield:'currencyCode',
						notefield:'currencyUnit',
						initload:true,
						cachename:_that.currencyCache
					}
				},null,mainData)
				
				if(_that.subEditorObj["title2"]){
					let configData = _that.subConfigData["title2"]
					let title = getEditorTitle("title2","sumCosts",configData)
					changeEditor("title2", "dataStr", {
						getWorkParam: 'getWorkParam',
						titleTemplate:title+":<%= sumCosts %>",
						subtitle1Template:"<%= cityName + address %>",
						subtitle2Template:"<%= startTime + '~' + endTime %>", 
						subtitle3Template:"<%= remark %>"
					}, null, mainData)
				}
				//赋值
				if(fileId){
					var fieldArr = getFormFields(mainData)
					fieldArr.push("id")
					var dataList = _that._.cloneDeep(res[4].value.dataList)
					_that.subEditorObj["title2"].workList = dataList
					_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "dataStr", JSON.stringify(dataList))
					_that.$set(_that.formdata, "dataStr", JSON.stringify(dataList))
					delete res[4].value.dataList
					for(var i in res[4].value){
						if(fieldArr.includes(i)){
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata, i, res[4].value[i])
							_that.$set(_that.formdata, i, res[4].value[i])
						}
					}
					if(_that.subEditorObj["title2"]){
						changeEditor("title2", "dataStr", {
							showDel: !_that.checkedit,
							showAdd:!_that.checkedit
						}, null, mainData)
					}
					//修改时初始化下拉框的值
					_that.$nextTick(function() {
						if(this.$refs.autoform){
							this.$refs.autoform.initSelectIndex('title1', 'payTypeId')
						}
					})
				}
				_that.$nextTick(function(){
					if(!_that.$refs.autoform.formdata.zposId){
						_that.$refs.autoform.initSelectVal('topinfo', 'zposId')
					}else{
						_that.$refs.autoform.initSelectIndex('topinfo', 'zposId')
					}
					if(!_that.$refs.autoform.formdata.keyPostId){
						_that.$refs.autoform.initSelectVal('title1', 'keyPostId')
					}else{
						_that.$refs.autoform.initSelectIndex('title1', 'keyPostId')
					}
				})
			}, options)
			
		}
	},
	onLoad(options) {
		let _that = this;
		_that.formdata.userId = this.userId;
		_that.initLoad(options);
	},
	onShow() {
		let _that = this;
		if (_that.$refs.autoform) {
			for (var fieldId in _that.subEditorObj) {
				var editor = _that.subEditorObj[fieldId];
				uni.getStorage({
					key: getWorkCacheKey(fieldId),
					success: function(res) {
						editor.workList = res.data;
						_that.onSubChange(editor)
						_that.getTime(editor)
						uni.removeStorage({
							key: getWorkCacheKey(fieldId)
						});
					}
				});
			}
			uni.getStorage({
				key: _that.userCacheKey,
				success: function(res) {
					if(res.data){
						let d = res.data
						var formdata  = _that.$refs.autoform.formdata
						formdata.keyUserId = d.id
						formdata.keyUserName = d.username
						formdata.keyPostId = d.salaryPosId
						formdata.keyPostName = d.salaryPosName
						formdata.keyInstId = d.salaryPosInstId
						formdata.keyInstName = d.salaryPosInstName
						_that.onSelectUser(d)
						uni.removeStorage({
							key: _that.userCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key: _that.bankUserCacheKey,
				success: function(res) {
					if(res.data){
						let d = res.data
						var formdata  = _that.$refs.autoform.formdata
						formdata.bankUserId = d.id
						formdata.bankUserName = d.username
						uni.removeStorage({
							key: _that.bankUserCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key:_that.currencyCache,
				success:(res)=>{
					let d = res.data
					let formdata = _that.$refs.autoform.formdata
					formdata.currencyId = d.id
					formdata.currencyName = d.codeNameUnit
					uni.removeStorage({
						key: _that.currencyCache
					})
				}
			})
		}
	}
};
</script>
<style></style>
